from fastapi import APIRouter, HTTPException, Query
from typing import Optional
from .models import OutOpenDoor, InOpenDoor, InChangePass, InPassWord, OutPassWord, OutChangePass
from .sub_utils import DoorControl
import asyncio
import time
import re

router = APIRouter(
    prefix="/DoorControl",
    tags=["门禁控制"]
)

dbDoor = DoorControl()


@router.get("/OpenDoor", response_model=OutOpenDoor)
async def openDoor(password: str = InOpenDoor):
    if password != dbDoor.getKeyPassWord():
        raise HTTPException(status_code=410, detail='密码错误，请重新输入')
    await dbDoor.setOpenStatus('开启')
    return {'status': dbDoor.getOpenStatus(), 'time': time.time() * 1000}


@router.get("/Input", response_model=OutPassWord)
async def inputPassword(single_pass: str = InPassWord):
    if re.search('^[0-9]$', single_pass) is None:
        raise HTTPException(status_code=412, detail='Api data handle fault!')
    dbDoor.setInputPassWord(single_pass)
    return {'password': dbDoor.getInputPassWord(), 'time': time.time() * 1000}


@router.get("/Del", response_model=OutPassWord)
async def delPassword():
    dbDoor.delInputPassWord()
    return {'password': dbDoor.getInputPassWord(), 'time': time.time() * 1000}


@router.get("/Change", response_model=OutChangePass)
async def changePassword(password: str = InChangePass):
    if not dbDoor.setKeyPassWord(password):
        raise HTTPException(status_code=408, detail='密码长度不对，请重新设置!')
    return {'status': True, 'time': time.time() * 1000}


@router.get('/CloseDoor', response_model=OutOpenDoor)
async def closeDoor():
    await dbDoor.setOpenStatus('关闭')
    return {'status': dbDoor.getOpenStatus(), 'time': time.time() * 1000}
